﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using SomeGame.Tools;

namespace SomeGame.Input {

    public static class InputManager {

        private static readonly IDictionary<Keys, Action> PressedContinuallyKeyMap = new Dictionary<Keys, Action>();
        private static readonly IDictionary<Keys, Action> PressedOnceKeyMap = new Dictionary<Keys, Action>();
        private static readonly IDictionary<Keys, Action> ReleasedKeyMap = new Dictionary<Keys, Action>();
        private static Action LeftMouseButtonMap;

        public static void MapPressedOnceKey(Keys key, Action action) {
            PressedOnceKeyMap.Add(key, action);
        }

        public static void MapPressedContinuallyKey(Keys key, Action action) {
            PressedContinuallyKeyMap.Add(key, action);
        }

        public static void MapReleasedKey(Keys key, Action action) {
            ReleasedKeyMap.Add(key, action);
        }

        public static void MapLeftMouseButton(Action action) {
            LeftMouseButtonMap = action;
        }

        public static void Update(GameTime gameTime) {

            for (int i = 0; i < GameEngine.PressedKeys.Length; i++) {
                Keys pressedKey = GameEngine.PressedKeys[i]; // Enums are value types.
                // Pressed once keys.
                if (PressedOnceKeyMap.ContainsKey(pressedKey) && 
                    GameEngine.PressedKeys.Contains(pressedKey) && 
                    !GameEngine.PreviousPressedKeys.Contains(pressedKey)) {
                    (PressedOnceKeyMap[pressedKey])();
                }
                // Continually pressed keys.
                if (PressedContinuallyKeyMap.ContainsKey(pressedKey) && // The Key is indeed one that should fire continually.
                    GameEngine.PressedKeys.Contains(pressedKey)) {      // The Key is currently pressed.
                    (PressedContinuallyKeyMap[pressedKey])();           // Fire
                }
            }

            // Released keys.
            for (int i = 0; i < GameEngine.PreviousPressedKeys.Length; i++) {
                Keys pressedKeyLastFrame = GameEngine.PreviousPressedKeys[i]; // Enums are value types.
                if (ReleasedKeyMap.ContainsKey(pressedKeyLastFrame) && 
                    !GameEngine.PressedKeys.Contains(pressedKeyLastFrame)) {
                    (ReleasedKeyMap[pressedKeyLastFrame])();
                }
            }

            // Mouse LeftButton.
            if (LeftMouseButtonMap != null && GameEngine.MouseState.LeftButton == ButtonState.Pressed) {
                LeftMouseButtonMap();
            }

        }

    }

    public enum MouseButton {

        Left,
        Right

    }

}